package com.xiaocg.juc.sync;

import java.util.Random;

public class TestTransferAccount {

    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, random.nextInt(4)+1);
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a,random.nextInt(4)+1);
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("total:"+(a.getAmount()+b.getAmount()));
    }
}

class Account{
    private int amount;

    public Account(int amount) {
        this.amount = amount;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public void transfer(Account a,int amount){
        synchronized (Account.class) {
            if (this.amount > amount) {
                this.setAmount(this.amount - amount);
                a.setAmount(a.getAmount() + amount);
            }
        }
    }
}
